#!/bin/bash
path=`dirname $0`
cd $path
base=`pwd`
platforms_dir=$base/../../scripts/platforms
echo platforms_dir=[$platforms_dir]
cmake_debug=
echo current dir is $base
usage ()
{
    echo "build.sh [options]"
    echo " -h                                       print help infomation"
    echo " -c                                       clean build"
    echo " -d                                       debug build"
    echo " -p [host | ]                             set target toolchain"
    exit 1
}

while getopts "cdhp:" arg
do
    case $arg in
        p)
        platform=$OPTARG;;
        c)
        clean="true";;
        d)
        cmake_debug="-DCMAKE_BUILD_TYPE=Debug"
        echo "CMAKE_BUILD_TYPE=Debug";;
        h)
        usage;;
        ?)
        echo $arg
        usage;;
    esac
done

# p-platform
if [ ! -n "$platform" ]; then
    platform="host"
elif [ "$platform" != "host" ]; then
    toolchain_def="-DCMAKE_TOOLCHAIN_FILE=$platforms_dir/$platform/toolchain.cmake" 
    setenv_file=$platforms_dir/$platform/setenv.sh
fi

out=$base/out/$platform

if [ "$clean" = "true" ]; then
    if [  -d "$out" ]; then
        rm -rf $out
        echo "clean build: removed folder "  $out
    fi
fi

[ -d $out ] || mkdir -p $out

echo "Build platform(-p)        : [$platform]" 
echo "out put directory is(-o)  : [$out]" 
        
echo "~~~~~~~~~~~~~~~~~"
echo "Starting build..."

cd $out
	
echo ""
echo "now run cmake for project " 
echo "setenv_file       : [$setenv_file]" 
if [ ! -n "$setenv_file" ]; then
	echo "host needn't setenv"
else
	source $setenv_file
fi
cmake $toolchain_def $base $cmake_debug
[ $? -eq 0 ] || exit $?
make
[ $? -eq 0 ] || exit $?

pwd
ls

echo "\033[32m <<<<<<<<<<<<<<<<<<<<<<<<<<<build pass!\033[0m"

exit 0

